import Vue from 'vue'
import Vuex from 'vuex'

// 1.安装插件
Vue.use(Vuex)

// 2.创建store对象并挂载到vue实例上
export default new Vuex.Store({
  state: {
    cartList: []
  },
  mutations: {
    // addCounter(payload) {
    //   payload.count++
    // }
  },
  actions: {
    addCart(context, payload) {
      return new Promise((resolve,reject) => {
        
      // 1.查找之前数组中是否有该商品
      let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)

      // 2.判断oldProduct
      if(oldProduct) { //数量+1
        // context.commit('addCounter',oldProduct)
        oldProduct.count += 1;
        resolve("当前商品数量+1")
        reject("商品已售完")
      } else { //添加新商品
        payload.count = 1;
        payload.checked = true;
        context.state.cartList.push(payload)
        resolve("添加了新的商品")
      }
      })
    }
  },
  modules: {
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    cartList(state) {
      return state.cartList
    }
  }
})
